package cn.pku.sirx.snad.ad.dao.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.Assert;

import cn.pku.sirx.snad.ad.dao.IAdContentDao;
import cn.pku.sirx.snad.ad.model.entity.AdContent;
import cn.pku.sirx.snad.ad.model.entity.KwAdRelation;

/**
 * @author WangXiao
 */
public class AdContentDaoImpl extends DaoImpl<AdContent> implements
		IAdContentDao {

	public AdContentDaoImpl() {
		super(AdContent.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AdContent> getByKeywords(Collection<String> keywords) {
		Assert.notNull(keywords);

		/*
		 * get ad group IDs
		 */
		DetachedCriteria criteria = DetachedCriteria
				.forClass(KwAdRelation.class);
		criteria.add(Restrictions.in("keywordString", keywords));
		criteria.setProjection(Projections.property("adGroupId"));
		List<Long> adGroupIds = getHibernateTemplate().findByCriteria(criteria);
		/*
		 * get ad contents
		 */
		if (adGroupIds.isEmpty()) {
			return Collections.emptyList();
		} else {
			criteria = DetachedCriteria.forClass(targetClass);
			criteria.add(Restrictions.in("adGroupId", adGroupIds));
			return get(criteria);
		}
	}

}
